프로토타입 패턴

JavaScript 프로토타입 패턴

JS에서 객체를 표현하는 5가지 방식과 프로토타입 체인

객체 표현 방식 5가지

1. Object Literal

const healthObj = {
  name: "달리기",
  lastTime: "PM10:12",
  showHealth() {
    console.log(this.name + "님, " + this.lastTime + "에 운동하셨네요");
  }
}

2. ES Classes (ES2015~)

const Health = class {
  constructor(name, healthTime) {
    this.name = name;
    this.healthTime = healthTime;
  }
  showHealth() {
    console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
  }
}

const ho = new Health("crong", "12:12");

3. Constructor Pattern

const Health = function(name, healthTime) {
  this.name = name;
  this.healthTime = healthTime;
  this.showHealth = function() {
    console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
  }
}

const ho = new Health("crong", "12:12");

4. Prototype Pattern

const Health = function(name, healthTime) {
  this.name = name;
  this.healthTime = healthTime;
}

Health.prototype.showHealth = function() {
  console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
}
myHealth.__proto__ === myHealth2.__proto__  // true

5. Object.create

const healthObj = {
  showHealth() {
    console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
  }
}

const ho = Object.create(healthObj, {
  name: { value: "crong" },
  healthTime: { value: "12:22" }
})

프로토타입 체인

myHealth
  ├── name: "달리기"
  └── __proto__: Health.prototype
        ├── showHealth: function
        └── __proto__: Object.prototype

언제 무엇을 사용하나?

상황 권장 방식
단일 객체, 재사용 불필요 Object Literal
여러 인스턴스 생성 필요 ES Classes (현대적, 권장)
메모리 최적화 필요 Prototype Pattern

관련 개념